\chapter{Chapter 5: Package Development and Management}

\section{Overview}

Package Development \& Management represents one of the most strategic and impactful task types in Claude Code development. These tasks involve converting scripts and code into installable packages, creating command-line interfaces, managing dependencies, and establishing distribution systems. This task type transforms scattered functionality into reusable, maintainable, and distributable software components.

\subsection{\textbf{Key Characteristics}}
\begin{itemize}
\item \textbf{Scope}: Script-to-package conversion, CLI creation, distribution setup, dependency management
\item \textbf{Complexity}: Medium to High (3-5 on complexity scale)
\item \textbf{Typical Duration}: Single session to multiple sessions spanning days or weeks
\item \textbf{Success Factors}: Proper architecture planning, systematic development, thorough testing, clear documentation
\item \textbf{Common Patterns}: Assessment → Planning → Structure Creation → CLI Development → Testing → Distribution Setup
\end{itemize}

\subsection{\textbf{When to Use This Task Type}}
\begin{itemize}
\item Converting standalone scripts into installable packages
\item Creating command-line tools and applications
\item Setting up package distribution systems (PyPI, pip install capability)
\item Managing complex dependency hierarchies
\item Establishing reusable code libraries
\item Creating MCP (Model Context Protocol) server packages
\item Building tools that integrate with existing ecosystems
\item Developing multi-component software systems
\end{itemize}

\subsection{\textbf{Typical Complexity and Duration}}

\textbf{Simple Packages (Complexity 3):}
\begin{itemize}
\item Single-script conversion to package
\item Basic CLI with limited functionality
\item Minimal dependencies
\item Duration: 2-4 hours, single session
\end{itemize}

\textbf{Medium Packages (Complexity 4):}
\begin{itemize}
\item Multi-module packages with CLI
\item Web server or API integration
\item Complex dependency management
\item Duration: 1-3 days across multiple sessions
\end{itemize}

\textbf{Complex Packages (Complexity 5):}
\begin{itemize}
\item Multi-package ecosystems
\item Advanced CLI with subcommands
\item Integration with external services
\item Duration: 1-2 weeks across many sessions
\end{itemize}

\section{Real-World Examples from Session Analysis}

\subsection{\textbf{Example 1: Script-to-Package Conversion - Claude Code Usage Monitor}}

\textbf{Initial Prompt:}
\begin{lstlisting}
convert workdir\_stats.py to a complete package which could install to system and use it with command: ccwork
\end{lstlisting}

\textbf{Follow-up Request:}
\begin{lstlisting}
add --serve to enable frontend website, optimize its exhibit performance
\end{lstlisting}

\textbf{Development Approach Taken:}
\begin{itemize}
\item \textbf{Assessment Phase}: Analyzed existing \texttt{workdir\_stats.py} script functionality
\item \textbf{Architecture Planning}: Designed package structure with CLI, web server, and core modules
\item \textbf{Package Structure Creation}: Created \texttt{ccwork/} package directory with proper \texttt{\textbf{init}.py}, \texttt{cli.py}, \texttt{core.py}, \texttt{server.py}
\item \textbf{CLI Development}: Implemented comprehensive command-line interface with 40+ options
\item \textbf{Web Integration}: Added FastAPI-based web dashboard with real-time WebSocket updates
\item \textbf{Distribution Setup}: Created \texttt{setup.py} with entry points for \texttt{ccwork} command
\item \textbf{Performance Optimization}: Implemented caching systems and efficient data processing
\end{itemize}

\textbf{Key Development Pattern:}
\begin{enumerate}
\item \textbf{Script Analysis}: Understanding existing functionality and limitations
\item \textbf{Package Architecture}: Designing modular structure for scalability
\item \textbf{CLI Design}: Creating intuitive command-line interface
\item \textbf{Web Integration}: Adding dashboard capabilities for enhanced usability
\item \textbf{Testing & Validation}: Ensuring package installation and functionality work correctly
\end{enumerate}

\subsection{\textbf{Example 2: Task Management CLI Creation}}

\textbf{Initial Prompt:}
\begin{lstlisting}
according to tm-prd.md, develop this task-manager software and process it with the git repository format such as create README.md, after that you can run \texttt{create\_git.sh https://gitee.com/suyuexinghen28/task-manager.git} to push this repository to gitee server.
\end{lstlisting}

\textbf{Follow-up Request:}
\begin{lstlisting}
rename this package to cc-task-manager, can support run simple command cctm
\end{lstlisting}

\textbf{Development Approach Taken:}
\begin{itemize}
\item \textbf{Requirements Analysis}: Parsed specification from \texttt{tm-prd.md}
\item \textbf{Package Creation}: Developed complete package structure from scratch
\item \textbf{CLI Implementation}: Created \texttt{cctm} command-line tool
\item \textbf{Git Integration}: Prepared repository for version control and distribution
\item \textbf{Documentation}: Created comprehensive README.md
\item \textbf{Distribution Preparation}: Set up for remote repository deployment
\end{itemize}

\textbf{Key Development Pattern:}
\begin{enumerate}
\item \textbf{Specification Review}: Understanding requirements from documentation
\item \textbf{Package Planning}: Designing complete software architecture
\item \textbf{Implementation}: Building core functionality and CLI interface
\item \textbf{Documentation}: Creating user and developer documentation
\item \textbf{Repository Setup}: Preparing for version control and distribution
\end{enumerate}

\subsection{\textbf{Example 3: Wiki.js Management Package}}

\textbf{Initial Prompt:}
\begin{lstlisting}
refer to docs/tomarkdown.org-2025-08-23T12-06-41.md, write a software to manage the wiki at wiki.js, my wiki.js API KEY is $WikiJS\_API\_KEY, you can configure this at .env
\end{lstlisting}

\textbf{Development Approach Taken:}
\begin{itemize}
\item \textbf{API Integration}: Integrated with Wiki.js GraphQL API
\item \textbf{Configuration Management}: Implemented \texttt{.env} file handling for API keys
\item \textbf{CLI Development}: Created comprehensive command-line interface for wiki management
\item \textbf{Error Handling}: Implemented robust error handling for network and API failures
\item \textbf{Package Distribution}: Set up proper package structure for installation
\end{itemize}

\textbf{Key Development Pattern:}
\begin{enumerate}
\item \textbf{API Research}: Understanding external service integration requirements
\item \textbf{Configuration Design}: Planning secure credential management
\item \textbf{CLI Architecture}: Designing user-friendly command structure
\item \textbf{Error Resilience}: Building robust error handling and recovery
\item \textbf{Package Finalization}: Ensuring reliable installation and usage
\end{enumerate}

\subsection{\textbf{Example 4: Multi-Client API Package Enhancement}}

\textbf{Initial Prompt:}
\begin{lstlisting}
similar to the qwen-client, let it also support ds-client which will call the deepseek API, the API key also configure at .env, you can use $DEEPSEEK\_API\_KEY
\end{lstlisting}

\textbf{Development Approach Taken:}
\begin{itemize}
\item \textbf{Extension Planning}: Analyzed existing package to understand architecture
\item \textbf{API Integration}: Added support for additional API service
\item \textbf{Configuration Enhancement}: Extended environment variable management
\item \textbf{Code Reuse}: Leveraged existing patterns for new functionality
\item \textbf{Testing}: Validated multi-client functionality
\end{itemize}

\textbf{Key Development Pattern:}
\begin{enumerate}
\item \textbf{Architecture Analysis}: Understanding existing package structure
\item \textbf{Feature Extension}: Adding new capabilities while maintaining compatibility
\item \textbf{Configuration Management}: Extending environment handling
\item \textbf{Pattern Replication}: Using consistent approaches for similar functionality
\item \textbf{Validation}: Testing enhanced package functionality
\end{enumerate}

\section{Templates and Procedures}

\subsection{Package Planning Template}

Use this template to systematically plan package development:

\begin{lstlisting}[language=bash]
\section{Package Development Planning Template}

\subsection{Project Overview}
\textbf{Package Name}: [descriptive-package-name]
\textbf{Primary Purpose}: [clear description of main functionality]
\textbf{Target Users}: [developers, end-users, data scientists, etc.]
\textbf{Complexity Level}: [3-5 based on scope and requirements]
\textbf{Estimated Duration}: [single session / multiple days / weeks]

\subsection{Requirements Analysis}
\textbf{Core Functionality}:
\begin{itemize}
\item [ ] [Primary feature 1]
\item [ ] [Primary feature 2]
\item [ ] [Primary feature 3]
\end{itemize}

\textbf{CLI Requirements}:
\begin{itemize}
\item [ ] Main command name: [command-name]
\item [ ] Subcommands needed: [list subcommands]
\item [ ] Configuration options: [config requirements]
\item [ ] Output formats: [human-readable, JSON, etc.]
\end{itemize}

\textbf{Integration Requirements}:
\begin{itemize}
\item [ ] External APIs: [list API dependencies]
\item [ ] Database systems: [if applicable]
\item [ ] File system operations: [file handling needs]
\item [ ] Network services: [web server, websockets, etc.]
\end{itemize}

\textbf{Environment Configuration}:
\begin{itemize}
\item [ ] Environment variables needed: [list variables]
\item [ ] Configuration files: [.env, config.yml, etc.]
\item [ ] Default values and fallbacks: [specify defaults]
\end{itemize}

\subsection{Distribution Strategy}
\textbf{Installation Method}:
\begin{itemize}
\item [ ] pip install from PyPI
\item [ ] Local development installation (pip install -e .)
\item [ ] System package managers
\item [ ] Direct script distribution
\end{itemize}

\textbf{Entry Points}:
\begin{itemize}
\item [ ] Console scripts: [command-name = package.module:function]
\item [ ] GUI applications: [if applicable]
\item [ ] MCP servers: [if applicable]
\end{itemize}

\textbf{Dependency Management}:
\begin{itemize}
\item [ ] Core dependencies: [list required packages]
\item [ ] Optional dependencies: [list optional packages]
\item [ ] Version constraints: [specify version requirements]
\item [ ] Development dependencies: [testing, linting tools]
\end{itemize}

\subsection{Success Criteria}
\textbf{Functional Requirements}:
\begin{itemize}
\item [ ] Package installs without errors
\item [ ] CLI commands execute successfully
\item [ ] Core functionality works as specified
\item [ ] Error handling is robust
\end{itemize}

\textbf{Quality Requirements}:
\begin{itemize}
\item [ ] Code follows style guidelines
\item [ ] Documentation is comprehensive
\item [ ] Tests cover critical functionality
\item [ ] Performance meets requirements
\end{itemize}
\end{lstlisting}

\subsection{Package Structure Template}

Use this structure as a foundation for new packages:

\begin{lstlisting}[language=bash]
\section{Standard Python Package Structure}

\subsection{Directory Layout}
\end{lstlisting}
package-name/
├── package\_name/           \# Main package directory
│   ├── \textbackslash\{\}textbf\{init\}.py        \# Package initialization
│   ├── cli.py             \# Command-line interface
│   ├── core.py            \# Core business logic
│   ├── config.py          \# Configuration management
│   ├── utils.py           \# Utility functions
│   └── server.py          \# Web server (if applicable)
├── tests/                 \# Test suite
│   ├── \textbackslash\{\}textbf\{init\}.py
│   ├── test\_cli.py
│   ├── test\_core.py
│   └── test\_integration.py
├── setup.py              \# Package configuration
├── requirements.txt      \# Dependencies
├── README.md            \# Documentation
├── .env.example         \# Environment configuration example
└── .gitignore          \# Git ignore rules
\begin{lstlisting}
\subsection{Key File Templates}

\subsubsection{setup.py Template}
\end{lstlisting}python
from setuptools import setup, find\_packages

with open("README.md", "r", encoding="utf-8") as fh:
    long\_description = fh.read()

with open("requirements.txt", "r", encoding="utf-8") as fh:
    requirements = [line.strip() for line in fh if line.strip() and not line.startswith("\#")]

setup(
    name="package-name",
    version="1.0.0",
    author="Author Name",
    author\_email="author@email.com",
    description="Brief package description",
    long\_description=long\_description,
    long\_description\_content\_type="text/markdown",
    url="https://github.com/username/package-name",
    packages=find\_packages(),
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
    ],
    python\_requires=">=3.8",
    install\_requires=requirements,
    entry\_points=\{
        "console\_scripts": [
            "command-name=package\_name.cli:main",
        ],
    \},
    extras\_require=\{
        "dev": [
            "pytest>=6.0",
            "pytest-cov>=2.0",
            "black>=21.0",
            "flake8>=3.8",
            "mypy>=0.800",
        ],
    \},
)
\begin{lstlisting}
\subsubsection{\textbf{init}.py Template}
\end{lstlisting}python
"""
Package Name - Brief Description

A comprehensive package for [main functionality].
"""

\textbf{version} = "1.0.0"
\textbf{author} = "Author Name"
\textbf{email} = "author@email.com"

from .core import MainClass, main\_function
from .cli import main as cli\_main

\textbf{all} = ["MainClass", "main\_function", "cli\_main"]
\begin{lstlisting}
\subsubsection{cli.py Template}
\end{lstlisting}python
"""
Command-line interface for package-name.
"""

import argparse
import sys
import logging
from typing import Optional, List

from .core import CoreClass
from .config import load\_config, ConfigError


def create\_parser() -> argparse.ArgumentParser:
    """Create and configure the argument parser."""
    parser = argparse.ArgumentParser(
        prog="command-name",
        description="Brief description of the tool",
        formatter\_class=argparse.RawDescriptionHelpFormatter,
    )
    
    parser.add\_argument(
        "--version",
        action="version",
        version=f"\%(prog)s \{\textbackslash\{\}textbf\{version\}\}",
    )
    
    parser.add\_argument(
        "-v", "--verbose",
        action="count",
        default=0,
        help="Increase verbosity (use multiple times)",
    )
    
    parser.add\_argument(
        "--config",
        type=str,
        help="Path to configuration file",
    )
    
    \# Add subcommands
    subparsers = parser.add\_subparsers(
        dest="command",
        title="Commands",
        description="Available commands",
        help="Use 'command-name <command> --help' for command-specific help",
    )
    
    \# Example subcommand
    cmd\_run = subparsers.add\_parser(
        "run",
        help="Run main functionality",
    )
    cmd\_run.add\_argument(
        "input",
        help="Input parameter",
    )
    
    return parser


def setup\_logging(verbose: int) -> None:
    """Configure logging based on verbosity level."""
    level = logging.WARNING
    if verbose == 1:
        level = logging.INFO
    elif verbose >= 2:
        level = logging.DEBUG
    
    logging.basicConfig(
        level=level,
        format="\%(asctime)s - \%(name)s - \%(levelname)s - \%(message)s",
    )


def main(argv: Optional[List[str]] = None) -> int:
    """Main CLI entry point."""
    parser = create\_parser()
    args = parser.parse\_args(argv)
    
    setup\_logging(args.verbose)
    logger = logging.getLogger(\textbackslash\{\}textbf\{name\})
    
    try:
        \# Load configuration
        config = load\_config(args.config)
        
        \# Initialize core functionality
        core = CoreClass(config)
        
        \# Execute command
        if args.command == "run":
            result = core.run(args.input)
            print(f"Result: \{result\}")
        else:
            parser.print\_help()
            return 1
            
        return 0
        
    except ConfigError as e:
        logger.error(f"Configuration error: \{e\}")
        return 1
    except Exception as e:
        logger.error(f"Unexpected error: \{e\}")
        if args.verbose >= 2:
            logger.exception("Full traceback:")
        return 1


if \textbackslash\{\}textbf\{name\} == "\textbackslash\{\}textbf\{main\}":
    sys.exit(main())
\begin{lstlisting}
\subsubsection{config.py Template}
\end{lstlisting}python
"""
Configuration management for package-name.
"""

import os
from pathlib import Path
from typing import Dict, Any, Optional
from dataclasses import dataclass, field
from dotenv import load\_dotenv


class ConfigError(Exception):
    """Configuration-related errors."""
    pass


@dataclass
class Config:
    """Package configuration."""
    
    \# Core settings
    debug: bool = False
    verbose: int = 0
    
    \# API settings
    api\_key: Optional[str] = None
    api\_url: str = "https://api.example.com"
    
    \# File paths
    data\_dir: Path = field(default\_factory=lambda: Path.home() / ".package-name")
    cache\_dir: Path = field(default\_factory=lambda: Path.home() / ".cache" / "package-name")
    
    \# Performance settings
    timeout: int = 30
    max\_retries: int = 3
    
    def \textbackslash\{\}textbf\{post\_init\}(self):
        """Validate configuration after initialization."""
        \# Ensure directories exist
        self.data\_dir.mkdir(parents=True, exist\_ok=True)
        self.cache\_dir.mkdir(parents=True, exist\_ok=True)
        
        \# Validate required settings
        if not self.api\_key:
            raise ConfigError("API key is required")


def load\_config(config\_path: Optional[str] = None) -> Config:
    """Load configuration from various sources."""
    
    \# Load environment variables
    env\_paths = [
        Path.cwd() / ".env",
        Path(\textbackslash\{\}textbf\{file\}).parent / ".env",
        Path.home() / ".package-name" / ".env",
    ]
    
    for env\_path in env\_paths:
        if env\_path.exists():
            load\_dotenv(env\_path)
            break
    
    \# Build configuration
    config\_data = \{
        "debug": os.getenv("DEBUG", "").lower() in ("true", "1", "yes"),
        "api\_key": os.getenv("API\_KEY"),
        "api\_url": os.getenv("API\_URL", "https://api.example.com"),
        "timeout": int(os.getenv("TIMEOUT", "30")),
        "max\_retries": int(os.getenv("MAX\_RETRIES", "3")),
    \}
    
    \# Load from config file if specified
    if config\_path:
        \# Implementation for loading from file (JSON, YAML, etc.)
        pass
    
    return Config(**config\_data)
\begin{lstlisting}

\end{lstlisting}

\subsection{Development Workflow Template}

Follow this systematic workflow for package development:

\section{Package Development Workflow}

\subsection{Phase 1: Project Assessment and Planning}
\textbf{Duration}: 15-30 minutes
\textbf{Objectives}: Understand requirements and plan approach

\textbf{Steps}:
\begin{enumerate}
\item \textbf{Requirement Analysis}
\end{enumerate}
\begin{itemize}
\item [ ] Review existing code or specifications
\item [ ] Identify core functionality requirements
\item [ ] Determine CLI interface needs
\item [ ] Assess external dependencies and integrations
\end{itemize}

\begin{enumerate}
\item \textbf{Architecture Planning}
\end{enumerate}
\begin{itemize}
\item [ ] Design package structure and module organization
\item [ ] Plan CLI command hierarchy and options
\item [ ] Identify configuration requirements
\item [ ] Plan error handling and logging strategy
\end{itemize}

\begin{enumerate}
\item \textbf{Implementation Strategy}
\end{enumerate}
\begin{itemize}
\item [ ] Choose development approach (iterative vs. big-bang)
\item [ ] Define testing strategy
\item [ ] Plan documentation approach
\item [ ] Set timeline and milestones
\end{itemize}

\subsection{Phase 2: Package Structure Creation}
\textbf{Duration}: 30-60 minutes
\textbf{Objectives}: Create foundation for package development

\textbf{Steps}:
\begin{enumerate}
\item \textbf{Directory Setup}
\end{enumerate}
\begin{itemize}
\item [ ] Create package directory structure
\item [ ] Initialize \texttt{\textbf{init}.py} files
\item [ ] Set up version control (git init, .gitignore)
\item [ ] Create basic README.md
\end{itemize}

\begin{enumerate}
\item \textbf{Configuration Files}
\end{enumerate}
\begin{itemize}
\item [ ] Create setup.py with basic configuration
\item [ ] Set up requirements.txt
\item [ ] Create .env.example for environment variables
\item [ ] Configure development tools (pytest, black, flake8)
\end{itemize}

\begin{enumerate}
\item \textbf{Module Stubs}
\end{enumerate}
\begin{itemize}
\item [ ] Create module files with basic structure
\item [ ] Define main classes and functions (stubs)
\item [ ] Set up import structure
\item [ ] Implement basic logging
\end{itemize}

\subsection{Phase 3: Core Functionality Implementation}
\textbf{Duration}: 2-6 hours (varies by complexity)
\textbf{Objectives}: Implement main package functionality

\textbf{Steps}:
\begin{enumerate}
\item \textbf{Core Logic Development}
\end{enumerate}
\begin{itemize}
\item [ ] Implement main business logic
\item [ ] Create data models and classes
\item [ ] Implement error handling
\item [ ] Add configuration management
\end{itemize}

\begin{enumerate}
\item \textbf{External Integrations}
\end{enumerate}
\begin{itemize}
\item [ ] Implement API clients
\item [ ] Add database connectivity (if needed)
\item [ ] Create file I/O operations
\item [ ] Add network service integrations
\end{itemize}

\begin{enumerate}
\item \textbf{Testing and Validation}
\end{enumerate}
\begin{itemize}
\item [ ] Write unit tests for core functionality
\item [ ] Test error conditions and edge cases
\item [ ] Validate external integrations
\item [ ] Performance testing (if applicable)
\end{itemize}

\subsection{Phase 4: CLI Development}
\textbf{Duration}: 1-3 hours
\textbf{Objectives}: Create user-friendly command-line interface

\textbf{Steps}:
\begin{enumerate}
\item \textbf{Parser Setup}
\end{enumerate}
\begin{itemize}
\item [ ] Create argument parser with main options
\item [ ] Add subcommands for different functions
\item [ ] Implement help documentation
\item [ ] Add version information
\end{itemize}

\begin{enumerate}
\item \textbf{Command Implementation}
\end{enumerate}
\begin{itemize}
\item [ ] Connect CLI arguments to core functionality
\item [ ] Implement output formatting (human-readable, JSON)
\item [ ] Add progress indicators for long operations
\item [ ] Implement interactive prompts (if needed)
\end{itemize}

\begin{enumerate}
\item \textbf{User Experience}
\end{enumerate}
\begin{itemize}
\item [ ] Add colored output for better readability
\item [ ] Implement verbose/quiet modes
\item [ ] Create comprehensive error messages
\item [ ] Add configuration file support
\end{itemize}

\subsection{Phase 5: Testing and Quality Assurance}
\textbf{Duration}: 1-2 hours
\textbf{Objectives}: Ensure package reliability and quality

\textbf{Steps}:
\begin{enumerate}
\item \textbf{Package Installation Testing}
\end{enumerate}
\begin{itemize}
\item [ ] Test pip install -e . (development mode)
\item [ ] Verify all entry points work correctly
\item [ ] Test in fresh virtual environment
\item [ ] Validate import statements
\end{itemize}

\begin{enumerate}
\item \textbf{Functionality Testing}
\end{enumerate}
\begin{itemize}
\item [ ] Run comprehensive test suite
\item [ ] Test all CLI commands and options
\item [ ] Verify error handling works correctly
\item [ ] Test with various input scenarios
\end{itemize}

\begin{enumerate}
\item \textbf{Quality Checks}
\end{enumerate}
\begin{itemize}
\item [ ] Run code formatter (black)
\item [ ] Check code style (flake8)
\item [ ] Run type checker (mypy) if using type hints
\item [ ] Review code coverage
\end{itemize}

\subsection{Phase 6: Documentation and Distribution}
\textbf{Duration}: 30-60 minutes
\textbf{Objectives}: Prepare for distribution and usage

\textbf{Steps}:
\begin{enumerate}
\item \textbf{Documentation}
\end{enumerate}
\begin{itemize}
\item [ ] Complete README.md with usage examples
\item [ ] Document all CLI commands and options
\item [ ] Create installation instructions
\item [ ] Add troubleshooting section
\end{itemize}

\begin{enumerate}
\item \textbf{Distribution Preparation}
\end{enumerate}
\begin{itemize}
\item [ ] Finalize setup.py configuration
\item [ ] Test package building (python setup.py sdist bdist\_wheel)
\item [ ] Prepare for PyPI upload (if applicable)
\item [ ] Create release notes
\end{itemize}

\begin{enumerate}
\item \textbf{Final Validation}
\end{enumerate}
\begin{itemize}
\item [ ] Install from built package
\item [ ] Test in production-like environment
\item [ ] Verify all dependencies are correctly specified
\item [ ] Confirm package metadata is correct
\end{itemize}

\section{Common Package Development Patterns}

\subsection{CLI Tool Development Patterns}

\textbf{Pattern 1: Subcommand Architecture}
\begin{lstlisting}[language=Python]
# Effective for packages with multiple distinct functions
def create\_parser():
    parser = argparse.ArgumentParser()
    subparsers = parser.add\_subparsers(dest="command")
    
    # List subcommand
    list\_parser = subparsers.add\_parser("list", help="List items")
    list\_parser.add\_argument("--format", choices=["table", "json"])
    
    # Create subcommand
    create\_parser = subparsers.add\_parser("create", help="Create item")
    create\_parser.add\_argument("name", help="Item name")
    
    return parser
\end{lstlisting}

\textbf{Pattern 2: Configuration Hierarchy}
\begin{lstlisting}[language=Python]
# Environment variables < Config file < Command line arguments
def load\_config(args):
    config = {}
    
    # 1. Load from environment
    config.update({
        "api\_key": os.getenv("API\_KEY"),
        "timeout": int(os.getenv("TIMEOUT", "30"))
    })
    
    # 2. Load from config file
    if args.config:
        config.update(load\_config\_file(args.config))
    
    # 3. Override with command line arguments
    if args.api\_key:
        config["api\_key"] = args.api\_key
    
    return config
\end{lstlisting}

\textbf{Pattern 3: Progressive Enhancement}
\begin{lstlisting}[language=Python]
# Start simple, add complexity as needed
class CLI:
    def \textbf{init}(self):
        self.verbose = False
        self.color\_output = True
    
    def run(self, args):
        if self.verbose:
            print(f"Running with args: {args}")
        
        result = self.core\_function(args)
        
        if self.color\_output:
            print(colored(result, "green"))
        else:
            print(result)
\end{lstlisting}

\subsection{Library vs Application Package Decisions}

\textbf{Choose Library Package When:}
\begin{itemize}
\item Code will be imported and used by other packages
\item Primary interface is programmatic APIs
\item Minimal or no CLI required
\item Focus on reusable components
\end{itemize}

\textbf{Choose Application Package When:}
\begin{itemize}
\item Primary usage is through command-line interface
\item End-users need a tool to accomplish tasks
\item Workflow orchestration is required
\item Integration with system tools needed
\end{itemize}

\textbf{Hybrid Approach:}
\begin{lstlisting}[language=Python]
# Package structure supporting both patterns
package\_name/
├── \textbf{init}.py      # Library interface
├── cli.py           # Application interface
├── core.py          # Shared functionality
└── api.py           # Programmatic API

# setup.py configuration
entry\_points={
    "console\_scripts": [
        "tool-name=package\_name.cli:main",  # Application
    ],

# Library usage: from package\_name import api
# Application usage: tool-name --help
\end{lstlisting}

\subsection{Dependency Management Strategies}

\textbf{Strategy 1: Minimal Dependencies}
\begin{lstlisting}[language=Python]
# Use standard library when possible
import json
import sqlite3
import urllib.request
from pathlib import Path

# Add dependencies only when standard library is insufficient
install\_requires=[
    "requests>=2.25.0",  # Only when urllib is too limited
    "click>=7.0",        # Only when argparse is too complex
]
\end{lstlisting}

\textbf{Strategy 2: Optional Dependencies}
\begin{lstlisting}[language=Python]
# setup.py
extras\_require={
    "web": ["fastapi>=0.68.0", "uvicorn>=0.15.0"],
    "database": ["sqlalchemy>=1.4.0", "alembic>=1.7.0"],
    "dev": ["pytest>=6.0", "black>=21.0", "flake8>=3.8"],

# In code
try:
    from fastapi import FastAPI
    HAS\_WEB = True
except ImportError:
    HAS\_WEB = False

def create\_web\_server():
    if not HAS\_WEB:
        raise ImportError("Web features require: pip install package[web]")
    # Implementation here
\end{lstlisting}

\textbf{Strategy 3: Version Pinning Strategy}
\begin{lstlisting}[language=Python]
# requirements.txt (for reproducible environments)
requests==2.28.1
fastapi==0.85.0
uvicorn==0.18.3

# setup.py (for compatibility ranges)
install\_requires=[
    "requests>=2.25.0,<3.0.0",
    "fastapi>=0.68.0,<1.0.0",
    "uvicorn>=0.15.0,<1.0.0",
]
\end{lstlisting}

\subsection{Testing and Quality Assurance Approaches}

\textbf{Approach 1: Layered Testing Strategy}
\begin{lstlisting}[language=Python]
# tests/test\_unit.py - Fast unit tests
def test\_core\_function():
    result = core\_function("input")
    assert result == "expected\_output"

# tests/test\_integration.py - Slower integration tests
def test\_api\_integration():
    client = APIClient(test\_config)
    response = client.get("/endpoint")
    assert response.status\_code == 200

# tests/test\_cli.py - CLI interface tests
def test\_cli\_command(runner):
    result = runner.invoke(cli, ["command", "arg"])
    assert result.exit\_code == 0
    assert "expected output" in result.output
\end{lstlisting}

\textbf{Approach 2: Quality Gates}
\begin{lstlisting}[language=Python]
# pytest.ini
[tool:pytest]
minversion = 6.0
addopts = --cov=package\_name --cov-report=term-missing --cov-fail-under=80
testpaths = tests

# tox.ini (if using tox)
[tox]
envlist = py38,py39,py310,py311,flake8,mypy

[testenv]
deps = pytest>=6.0
       pytest-cov>=2.0
commands = pytest

[testenv:flake8]
deps = flake8>=3.8
commands = flake8 package\_name tests

[testenv:mypy]
deps = mypy>=0.800
commands = mypy package\_name
\end{lstlisting}

\section{Best Practices}

\subsection{How to Structure Package Development Conversations with Claude}

\textbf{Best Practice 1: Start with Clear Requirements}
\begin{lstlisting}
✓ Good: "Convert my workdir\_stats.py script into an installable package with CLI command 'ccwork' that supports both local analysis and web dashboard via --serve option"

✗ Poor: "Make this into a package"
\end{lstlisting}

\textbf{Best Practice 2: Specify Architecture Preferences Early}
\begin{lstlisting}
✓ Good: "Create a package with separate modules for CLI (cli.py), core logic (core.py), and web server (server.py). Use FastAPI for the web interface."

✗ Poor: "Just make it work"
\end{lstlisting}

\textbf{Best Practice 3: Request Iterative Development}
\begin{lstlisting}
✓ Good: "First create the basic package structure and CLI, then we'll add the web server functionality"

✗ Poor: "Build everything at once"
\end{lstlisting}

\textbf{Best Practice 4: Be Specific About Entry Points}
\begin{lstlisting}
✓ Good: "The package should install a command called 'cctm' that supports subcommands: 'cctm list', 'cctm create', 'cctm delete'"

✗ Poor: "Make it have commands"
\end{lstlisting}

\subsection{When to Use Different Packaging Approaches}

\textbf{Simple Script Packaging:}
\begin{itemize}
\item Use when converting single-file scripts
\item Minimal CLI requirements
\item Few or no dependencies
\item Example: utility scripts, data processors
\end{itemize}

\textbf{Full Application Packaging:}
\begin{itemize}
\item Use for complex tools with multiple features
\item Rich CLI with subcommands
\item Web interfaces or APIs
\item Example: monitoring tools, content management systems
\end{itemize}

\textbf{Library Packaging:}
\begin{itemize}
\item Use for code intended to be imported
\item Minimal CLI (maybe just for demos)
\item Focus on API design
\item Example: data analysis libraries, API clients
\end{itemize}

\subsection{Common Pitfalls and Anti-Patterns to Avoid}

\textbf{Anti-Pattern 1: Monolithic CLI}
\begin{lstlisting}[language=Python]
# \\textcolor{red
def main():
    if args.command == "list":
        # 200 lines of list logic
    elif args.command == "create":
        # 150 lines of create logic
    # ... continues for 500+ lines

# \\textcolor{green
def main():
    commands = {
        "list": handle\_list,
        "create": handle\_create,
        "delete": handle\_delete,

    handler = commands.get(args.command)
    if handler:
        return handler(args)
    else:
        parser.print\_help()
\end{lstlisting}

\textbf{Anti-Pattern 2: Hard-coded Configuration}
\begin{lstlisting}[language=Python]
# \\textcolor{red
API\_KEY = "sk-1234567890abcdef"
BASE\_URL = "https://api.example.com"

# \\textcolor{green
import os
API\_KEY = os.getenv("API\_KEY")
BASE\_URL = os.getenv("BASE\_URL", "https://api.example.com")
\end{lstlisting}

\textbf{Anti-Pattern 3: Ignoring Error Handling}
\begin{lstlisting}[language=Python]
# \\textcolor{red
try:
    result = risky\_operation()
except:
    print("Something went wrong")

# \\textcolor{green
try:
    result = risky\_operation()
except ConnectionError as e:
    logger.error(f"Network error: {e}")
    sys.exit(1)
except ValueError as e:
    logger.error(f"Invalid input: {e}")
    sys.exit(2)
\end{lstlisting}

\textbf{Anti-Pattern 4: Incomplete Package Metadata}
\begin{lstlisting}[language=Python]
# \\textcolor{red
setup(
    name="mypackage",
    packages=find\_packages(),
)

# \\textcolor{green
setup(
    name="mypackage",
    version="1.0.0",
    author="Author Name",
    description="Clear description",
    long\_description=long\_description,
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
    ],
    python\_requires=">=3.8",
    install\_requires=requirements,
    entry\_points={
        "console\_scripts": [
            "mycommand=mypackage.cli:main",
        ],
    },
)
\end{lstlisting}

\subsection{Integration with Existing Codebases}

\textbf{Integration Strategy 1: Gradual Migration}
\begin{lstlisting}[language=Python]
# Phase 1: Create package structure alongside existing code
project/
├── legacy\_script.py    # Existing script
├── mypackage/         # New package
│   ├── \textbf{init}.py
│   ├── core.py        # Refactored logic from legacy script
│   └── cli.py         # New CLI interface

# Phase 2: Migrate functionality gradually
# Phase 3: Deprecate legacy script
\end{lstlisting}

\textbf{Integration Strategy 2: Wrapper Approach}
\begin{lstlisting}[language=Python]
# Keep existing functionality, add package interface
class LegacyWrapper:
    def \textbf{init}(self, legacy\_function):
        self.legacy\_function = legacy\_function
    
    def enhanced\_method(self, \textit{args, }*kwargs):
        # Add validation, logging, error handling
        try:
            return self.legacy\_function(\textit{args, }*kwargs)
        except Exception as e:
            logger.error(f"Legacy function error: {e}")
            raise
\end{lstlisting}

\section{Advanced Techniques}

\subsection{Multi-Package Development}

\textbf{Strategy: Monorepo with Independent Packages}
\begin{lstlisting}
packages/
├── shared-utils/          # Common utilities
│   ├── setup.py
│   └── shared\_utils/
├── api-client/            # API client package
│   ├── setup.py
│   └── api\_client/
├── cli-tool/              # CLI application
│   ├── setup.py
│   └── cli\_tool/
└── web-dashboard/         # Web interface
    ├── setup.py
    └── web\_dashboard/
\end{lstlisting}

\textbf{Cross-Package Dependencies:}
\begin{lstlisting}[language=Python]
# api-client/setup.py
install\_requires=[
    "shared-utils>=1.0.0",
    "requests>=2.25.0",
]

# cli-tool/setup.py
install\_requires=[
    "shared-utils>=1.0.0",
    "api-client>=1.0.0",
    "click>=7.0",
]
\end{lstlisting}

\subsection{Complex Dependency Management}

\textbf{Strategy: Dependency Injection Pattern}
\begin{lstlisting}[language=Python]
# core.py
class ServiceManager:
    def \textbf{init}(self):
        self.\_services = {}
    
    def register(self, name, service):
        self.\_services[name] = service
    
    def get(self, name):
        return self.\_services[name]

# cli.py
def main():
    services = ServiceManager()
    
    # Register services based on available dependencies
    try:
        from .web import WebService
        services.register("web", WebService())
    except ImportError:
        pass
    
    try:
        from .database import DatabaseService
        services.register("database", DatabaseService())
    except ImportError:
        pass
    
    # Use services if available
    if services.get("web"):
        # Enable web features
        pass
\end{lstlisting}

\subsection{Performance Optimization for Packages}

\textbf{Optimization 1: Lazy Loading}
\begin{lstlisting}[language=Python]
# \textbf{init
def \textbf{getattr}(name):
    if name == "expensive\_module":
        from . import expensive\_module
        return expensive\_module
    raise AttributeError(f"module {\textbf{name}} has no attribute {name}")

# Usage: Module only loaded when first accessed
from mypackage import expensive\_module  # Triggers loading
\end{lstlisting}

\textbf{Optimization 2: Caching Strategies}
\begin{lstlisting}[language=Python]
from functools import lru\_cache
import pickle
from pathlib import Path

class CacheManager:
    def \textbf{init}(self, cache\_dir):
        self.cache\_dir = Path(cache\_dir)
        self.cache\_dir.mkdir(exist\_ok=True)
    
    def get(self, key):
        cache\_file = self.cache\_dir / f"{key}.pkl"
        if cache\_file.exists():
            return pickle.loads(cache\_file.read\_bytes())
        return None
    
    def set(self, key, value, ttl=3600):
        cache\_file = self.cache\_dir / f"{key}.pkl"
        cache\_file.write\_bytes(pickle.dumps(value))

@lru\_cache(maxsize=128)
def expensive\_computation(params):
    # Expensive operation here
    return result
\end{lstlisting}

\subsection{Distribution and Deployment Strategies}

\textbf{Strategy 1: PyPI Distribution}
\begin{lstlisting}[language=Python]
# setup.py for PyPI
setup(
    name="unique-package-name",
    version="1.0.0",
    packages=find\_packages(),
    install\_requires=requirements,
    python\_requires=">=3.8",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3",
    ],
)

# Build and upload commands:
# python setup.py sdist bdist\_wheel
# twine upload dist/*
\end{lstlisting}

\textbf{Strategy 2: Docker Distribution}
\begin{lstlisting}[language=bash]
# Dockerfile for containerized distribution
FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
RUN pip install -e .

ENTRYPOINT ["mycommand"]
CMD ["--help"]
\end{lstlisting}

\textbf{Strategy 3: System Package Integration}
\begin{lstlisting}[language=Python]
# Generate system packages (DEB/RPM)
# Using stdeb for Debian packages:
# python setup.py --command-packages=stdeb.command bdist\_deb

# setup.cfg
[aliases]
deb\_dist = --dist-dir=deb\_dist bdist\_deb
rpm\_dist = --dist-dir=rpm\_dist bdist\_rpm
\end{lstlisting}

This chapter provides a comprehensive foundation for package development and management with Claude Code. The templates, patterns, and best practices outlined here have been proven effective in real-world development sessions and provide a systematic approach to creating robust, maintainable packages that integrate well with the broader Python ecosystem.